// Main data structures
let students = [
    { id: 1, name: 'Alice', score: 88, enrolledCourses: [], completedCourses: [] },
    { id: 2, name: 'Bob', score: 92, enrolledCourses: [], completedCourses: [] },
    { id: 3, name: 'Charlie', score: 85, enrolledCourses: [], completedCourses: [] },
    { id: 4, name: 'David', score: 90, enrolledCourses: [], completedCourses: [] }
];

const courses = {
    "CS101": { name: "Introduction to Programming", credits: 3, prerequisites: [] },
    "MATH201": { name: "Discrete Mathematics", credits: 4, prerequisites: [] },
    "CS250": { name: "Data Structures", credits: 3, prerequisites: ["CS101", "MATH201"] },
    "CS300": { name: "Algorithms", credits: 3, prerequisites: ["CS250"] },
    "CS350": { name: "Database Systems", credits: 3, prerequisites: ["CS250"] }
};

// Load grades from grades.json (simulated)
let gradesPerCourse = {
    "CS101": {
        1: [85, 90, 78],
        2: [90, 88, 92],
        3: [78, 85, 80],
        4: [88, 84, 89]
    },
    "MATH201": {
        1: [88, 85, 90],
        2: [85, 87, 88],
        3: [90, 92, 89],
        4: [87, 84, 86]
    },
    "CS250": {
        1: [91, 89, 92],
        2: [89, 87, 90],
        3: [87, 85, 88],
        4: [90, 88, 91]
    }
};

// Scheduling system
const courseSchedule = [
    { courseCode: "CS101", day: "Monday", startTime: "09:00", endTime: "11:00", classroom: "CS-101", instructor: "Prof. Smith" },
    { courseCode: "MATH201", day: "Tuesday", startTime: "10:00", endTime: "12:00", classroom: "MATH-202", instructor: "Prof. Johnson" },
    { courseCode: "CS250", day: "Wednesday", startTime: "13:00", endTime: "15:00", classroom: "CS-105", instructor: "Prof. Williams" }
];

const instructors = [
    { id: 1, name: "Prof. Smith", courses: ["CS101"], availability: ["Monday", "Wednesday", "Friday"] },
    { id: 2, name: "Prof. Johnson", courses: ["MATH201"], availability: ["Tuesday", "Thursday"] },
    { id: 3, name: "Prof. Williams", courses: ["CS250", "CS300"], availability: ["Monday", "Wednesday"] }
];

// Initialize the page
document.addEventListener('DOMContentLoaded', function() {
    populateStudentDropdown();
    displayStudents();
    displayPrerequisites();
    displayCourseSchedule();
    
    // Add event listeners
    document.getElementById('addStudent').addEventListener('click', addNewStudent);
    document.getElementById('sortByName').addEventListener('click', sortStudentsByName);
    document.getElementById('sortByScore').addEventListener('click', sortStudentsByScore);
    document.getElementById('sortByCourseGrade').addEventListener('change', handleCourseGradeSort);
    document.getElementById('addPrerequisite').addEventListener('click', addPrerequisite);
    document.getElementById('removePrerequisite').addEventListener('click', removePrerequisite);
    document.getElementById('checkEligibility').addEventListener('click', checkEligibility);
    document.getElementById('processEnrollment').addEventListener('click', processEnrollment);
    document.getElementById('completeCourse').addEventListener('click', completeCourse);
    document.getElementById('checkScheduleConflict').addEventListener('click', checkScheduleConflict);
    document.getElementById('saveSchedule').addEventListener('click', saveSchedule);
    document.getElementById('rescheduleCourse').addEventListener('click', rescheduleCourse);
});

// Student Management Functions
function populateStudentDropdown() {
    const dropdown = document.getElementById('enrollStudent');
    dropdown.innerHTML = '<option value="">Select a student</option>';
    
    students.forEach(student => {
        const option = document.createElement('option');
        option.value = student.id;
        option.textContent = `${student.name} (ID: ${student.id})`;
        dropdown.appendChild(option);
    });
}

function displayStudents() {
    const tableBody = document.getElementById('studentsTable').getElementsByTagName('tbody')[0];
    tableBody.innerHTML = '';

    students.forEach(student => {
        const row = tableBody.insertRow();
        
        const cellName = row.insertCell(0);
        cellName.textContent = student.name;
        
        const cellScore = row.insertCell(1);
        cellScore.textContent = student.score;
        
        const cellEnrolled = row.insertCell(2);
        cellEnrolled.textContent = student.enrolledCourses.join(', ') || 'None';
        
        const cellCompleted = row.insertCell(3);
        cellCompleted.textContent = student.completedCourses.join(', ') || 'None';
    });
}

function addNewStudent() {
    const name = document.getElementById('studentName').value.trim();
    const score = parseInt(document.getElementById('studentScore').value);
    const feedback = document.getElementById('addStudentFeedback');

    if (!name || isNaN(score) || score < 0 || score > 100) {
        feedback.textContent = 'Please enter a valid name and score (0-100).';
        feedback.style.color = 'red';
        return;
    }

    const newId = students.length > 0 ? Math.max(...students.map(s => s.id)) + 1 : 1;
    students.push({
        id: newId,
        name: name,
        score: score,
        enrolledCourses: [],
        completedCourses: []
    });

    feedback.textContent = `Student ${name} added successfully with ID ${newId}.`;
    feedback.style.color = 'green';

    document.getElementById('studentName').value = '';
    document.getElementById('studentScore').value = '';

    populateStudentDropdown();
    displayStudents();
}

// Sorting Functions
function sortStudentsByName() {
    students.sort((a, b) => a.name.localeCompare(b.name));
    displayStudents();
}

function sortStudentsByScore() {
    students.sort((a, b) => b.score - a.score);
    displayStudents();
}

function sortStudentsByCourseGrade(courseCode) {
    const studentsWithGrades = students.map(student => {
        const grades = gradesPerCourse[courseCode][student.id] || [];
        const avgGrade = grades.length > 0 ? 
            grades.reduce((sum, grade) => sum + grade, 0) / grades.length : 0;
        return { ...student, avgGrade };
    });
    
    studentsWithGrades.sort((a, b) => b.avgGrade - a.avgGrade);
    
    const tableBody = document.getElementById('studentsTable').getElementsByTagName('tbody')[0];
    tableBody.innerHTML = '';

    studentsWithGrades.forEach(student => {
        const row = tableBody.insertRow();
        
        const cellName = row.insertCell(0);
        cellName.textContent = student.name;
        
        const cellScore = row.insertCell(1);
        cellScore.textContent = student.avgGrade.toFixed(1);
        
        const cellEnrolled = row.insertCell(2);
        cellEnrolled.textContent = student.enrolledCourses.join(', ') || 'None';
        
        const cellCompleted = row.insertCell(3);
        cellCompleted.textContent = student.completedCourses.join(', ') || 'None';
    });
}

function handleCourseGradeSort(event) {
    const courseCode = event.target.value;
    if (courseCode) {
        sortStudentsByCourseGrade(courseCode);
    } else {
        displayStudents();
    }
}

// Prerequisite Management
function displayPrerequisites() {
    const displayDiv = document.getElementById('prerequisiteDisplay');
    displayDiv.innerHTML = '';

    for (const courseCode in courses) {
        const course = courses[courseCode];
        const prereqList = course.prerequisites.length > 0
            ? course.prerequisites.map(p => `${p} - ${courses[p].name}`).join(', ')
            : 'No prerequisites';

        const courseDiv = document.createElement('div');
        courseDiv.innerHTML = `<strong>${courseCode} - ${course.name}:</strong> ${prereqList}`;
        courseDiv.style.marginBottom = '10px';
        displayDiv.appendChild(courseDiv);
    }
}

function createsCircularDependency(courseCode, prereqCode) {
    const visited = new Set();
    const queue = [prereqCode];
    
    while (queue.length > 0) {
        const current = queue.shift();
        if (current === courseCode) return true;
        
        if (!visited.has(current)) {
            visited.add(current);
            const currentPrereqs = courses[current]?.prerequisites || [];
            queue.push(...currentPrereqs);
        }
    }
    
    return false;
}

function addPrerequisite() {
    const courseCode = document.getElementById('courseForPrereq').value;
    const prereqCode = document.getElementById('prereqToAdd').value;
    const feedback = document.getElementById('prereqFeedback');

    if (!courseCode || !prereqCode) {
        feedback.textContent = 'Please select both a course and a prerequisite.';
        feedback.style.color = 'red';
        return;
    }

    if (courseCode === prereqCode) {
        feedback.textContent = 'A course cannot be a prerequisite for itself.';
        feedback.style.color = 'red';
        return;
    }

    if (courses[courseCode].prerequisites.includes(prereqCode)) {
        feedback.textContent = 'This prerequisite relationship already exists.';
        feedback.style.color = 'orange';
        return;
    }

    if (createsCircularDependency(courseCode, prereqCode)) {
        feedback.textContent = 'Cannot add this prerequisite as it would create a circular dependency.';
        feedback.style.color = 'red';
        return;
    }

    courses[courseCode].prerequisites.push(prereqCode);
    feedback.textContent = `Added ${prereqCode} as a prerequisite for ${courseCode}.`;
    feedback.style.color = 'green';

    displayPrerequisites();
}

function removePrerequisite() {
    const courseCode = document.getElementById('courseForPrereq').value;
    const prereqCode = document.getElementById('prereqToAdd').value;
    const feedback = document.getElementById('prereqFeedback');

    if (!courseCode || !prereqCode) {
        feedback.textContent = 'Please select both a course and a prerequisite.';
        feedback.style.color = 'red';
        return;
    }

    const index = courses[courseCode].prerequisites.indexOf(prereqCode);
    if (index === -1) {
        feedback.textContent = 'This prerequisite relationship does not exist.';
        feedback.style.color = 'orange';
        return;
    }

    courses[courseCode].prerequisites.splice(index, 1);
    feedback.textContent = `Removed ${prereqCode} as a prerequisite for ${courseCode}.`;
    feedback.style.color = 'green';

    displayPrerequisites();
}

// Enrollment System
function checkPrerequisites(studentId, courseCode) {
    const student = students.find(s => s.id === studentId);
    if (!student) return false;
    
    const requiredPrereqs = courses[courseCode].prerequisites;
    if (requiredPrereqs.length === 0) return true;
    
    return requiredPrereqs.every(prereq => 
        student.completedCourses.includes(prereq)
    );
}

function checkEligibility() {
    const studentId = parseInt(document.getElementById('enrollStudent').value);
    const courseCode = document.getElementById('courseToEnroll').value;
    const feedback = document.getElementById('enrollmentFeedback');
    
    if (!studentId || !courseCode) {
        feedback.textContent = 'Please select both student and course';
        feedback.style.color = 'red';
        return;
    }
    
    if (checkPrerequisites(studentId, courseCode)) {
        feedback.textContent = 'Student meets all prerequisites for this course.';
        feedback.style.color = 'green';
    } else {
        const missingPrereqs = courses[courseCode].prerequisites.filter(
            prereq => !students.find(s => s.id === studentId).completedCourses.includes(prereq)
        );
        feedback.textContent = `Student is missing prerequisites: ${missingPrereqs.join(', ')}`;
        feedback.style.color = 'red';
    }
}

function processEnrollment() {
    const studentId = parseInt(document.getElementById('enrollStudent').value);
    const courseCode = document.getElementById('courseToEnroll').value;
    const feedback = document.getElementById('enrollmentFeedback');
    
    if (!studentId || !courseCode) {
        feedback.textContent = 'Please select both student and course';
        feedback.style.color = 'red';
        return;
    }
    
    const student = students.find(s => s.id === studentId);
    if (!student) {
        feedback.textContent = 'Student not found';
        feedback.style.color = 'red';
        return;
    }
    
    if (student.enrolledCourses.includes(courseCode)) {
        feedback.textContent = 'Student is already enrolled in this course';
        feedback.style.color = 'orange';
        return;
    }
    
    if (checkPrerequisites(studentId, courseCode)) {
        student.enrolledCourses.push(courseCode);
        feedback.textContent = 'Enrollment successful!';
        feedback.style.color = 'green';
        displayStudents();
    } else {
        feedback.textContent = 'Enrollment failed - prerequisites not met';
        feedback.style.color = 'red';
    }
}

function completeCourse() {
    const studentId = parseInt(document.getElementById('enrollStudent').value);
    const courseCode = document.getElementById('courseToEnroll').value;
    const feedback = document.getElementById('enrollmentFeedback');
    
    if (!studentId || !courseCode) {
        feedback.textContent = 'Please select both student and course';
        feedback.style.color = 'red';
        return;
    }
    
    const student = students.find(s => s.id === studentId);
    if (!student) {
        feedback.textContent = 'Student not found';
        feedback.style.color = 'red';
        return;
    }
    
    if (!student.enrolledCourses.includes(courseCode)) {
        feedback.textContent = 'Student is not enrolled in this course';
        feedback.style.color = 'red';
        return;
    }
    
    if (student.completedCourses.includes(courseCode)) {
        feedback.textContent = 'Student has already completed this course';
        feedback.style.color = 'orange';
        return;
    }
    
    // Remove from enrolled, add to completed
    student.enrolledCourses = student.enrolledCourses.filter(c => c !== courseCode);
    student.completedCourses.push(courseCode);
    
    // Update student score based on course grades (simplified)
    const grades = gradesPerCourse[courseCode]?.[studentId] || [];
    if (grades.length > 0) {
        const avgGrade = grades.reduce((sum, grade) => sum + grade, 0) / grades.length;
        student.score = Math.max(student.score, avgGrade); // Keep their highest score
    }
    
    feedback.textContent = `Course ${courseCode} marked as completed for ${student.name}`;
    feedback.style.color = 'green';
    displayStudents();
}

// Scheduling System
function displayCourseSchedule() {
    const tableBody = document.getElementById('courseScheduleTable').getElementsByTagName('tbody')[0];
    tableBody.innerHTML = '';
    
    courseSchedule.forEach(schedule => {
        const row = tableBody.insertRow();
        
        const cellCourse = row.insertCell(0);
        cellCourse.textContent = `${schedule.courseCode} - ${courses[schedule.courseCode].name}`;
        
        const cellDay = row.insertCell(1);
        cellDay.textContent = schedule.day;
        
        const cellTime = row.insertCell(2);
        cellTime.textContent = `${schedule.startTime} - ${schedule.endTime}`;
        
        const cellClassroom = row.insertCell(3);
        cellClassroom.textContent = schedule.classroom;
        
        const cellInstructor = row.insertCell(4);
        cellInstructor.textContent = schedule.instructor || "To be assigned";
    });
}

function hasScheduleConflict(newSchedule, ignoreCourse = null) {
    return courseSchedule.some(existing => {
        if (ignoreCourse && existing.courseCode === ignoreCourse) return false;
        
        // Same classroom and overlapping time
        if (existing.classroom === newSchedule.classroom && 
            existing.day === newSchedule.day &&
            ((newSchedule.startTime >= existing.startTime && newSchedule.startTime < existing.endTime) ||
             (newSchedule.endTime > existing.startTime && newSchedule.endTime <= existing.endTime) ||
             (newSchedule.startTime <= existing.startTime && newSchedule.endTime >= existing.endTime))) {
            return true;
        }
        
        return false;
    });
}

function checkScheduleConflict() {
    const courseCode = document.getElementById('schedulingCourse').value;
    const day = document.getElementById('scheduleDay').value;
    const startTime = document.getElementById('startTime').value;
    const endTime = document.getElementById('endTime').value;
    const classroom = document.getElementById('classroom').value;
    const feedback = document.getElementById('schedulingFeedback');
    
    if (!courseCode || !classroom) {
        feedback.textContent = 'Please select a course and enter a classroom';
        feedback.style.color = 'red';
        return;
    }
    
    const newSchedule = { courseCode, day, startTime, endTime, classroom };
    
    if (hasScheduleConflict(newSchedule)) {
        feedback.textContent = 'Conflict detected with existing schedule!';
        feedback.style.color = 'red';
    } else {
        feedback.textContent = 'No conflicts detected with current schedule';
        feedback.style.color = 'green';
    }
}

function saveSchedule() {
    const courseCode = document.getElementById('schedulingCourse').value;
    const day = document.getElementById('scheduleDay').value;
    const startTime = document.getElementById('startTime').value;
    const endTime = document.getElementById('endTime').value;
    const classroom = document.getElementById('classroom').value;
    const feedback = document.getElementById('schedulingFeedback');
    
    if (!courseCode || !classroom) {
        feedback.textContent = 'Please select a course and enter a classroom';
        feedback.style.color = 'red';
        return;
    }
    
    // Find an available instructor
    const availableInstructors = instructors.filter(instructor => 
        instructor.courses.includes(courseCode) && 
        instructor.availability.includes(day)
    );
    
    if (availableInstructors.length === 0) {
        feedback.textContent = 'No available instructors for this course on the selected day';
        feedback.style.color = 'red';
        return;
    }
    
    const newSchedule = { 
        courseCode, 
        day, 
        startTime, 
        endTime, 
        classroom,
        instructor: availableInstructors[0].name
    };
    
    if (hasScheduleConflict(newSchedule)) {
        feedback.textContent = 'Cannot save schedule - conflict detected!';
        feedback.style.color = 'red';
        return;
    }
    
    // Check if this course already has a schedule
    const existingIndex = courseSchedule.findIndex(s => s.courseCode === courseCode);
    if (existingIndex >= 0) {
        feedback.textContent = 'This course already has a schedule. Use reschedule instead.';
        feedback.style.color = 'orange';
        return;
    }
    
    courseSchedule.push(newSchedule);
    feedback.textContent = 'Schedule saved successfully!';
    feedback.style.color = 'green';
    displayCourseSchedule();
}

function rescheduleCourse() {
    const courseCode = document.getElementById('schedulingCourse').value;
    const day = document.getElementById('scheduleDay').value;
    const startTime = document.getElementById('startTime').value;
    const endTime = document.getElementById('endTime').value;
    const classroom = document.getElementById('classroom').value;
    const feedback = document.getElementById('schedulingFeedback');
    
    if (!courseCode) {
        feedback.textContent = 'Please select a course to reschedule';
        feedback.style.color = 'red';
        return;
    }
    
    const existingIndex = courseSchedule.findIndex(s => s.courseCode === courseCode);
    if (existingIndex === -1) {
        feedback.textContent = 'This course does not have an existing schedule to reschedule';
        feedback.style.color = 'red';
        return;
    }
    
    const newSchedule = { 
        ...courseSchedule[existingIndex],
        day: day || courseSchedule[existingIndex].day,
        startTime: startTime || courseSchedule[existingIndex].startTime,
        endTime: endTime || courseSchedule[existingIndex].endTime,
        classroom: classroom || courseSchedule[existingIndex].classroom
    };
    
    if (hasScheduleConflict(newSchedule, courseCode)) {
        feedback.textContent = 'Cannot reschedule - conflict detected with new parameters!';
        feedback.style.color = 'red';
        return;
    }
    
    courseSchedule[existingIndex] = newSchedule;
    feedback.textContent = 'Course rescheduled successfully!';
    feedback.style.color = 'green';
    displayCourseSchedule();
}